package com.onlinevideo.filter;

import com.onlinevideo.data.MyConst;
import com.onlinevideo.entity.Authority;
import com.onlinevideo.entity.RoleAuthorityDTO;
import com.onlinevideo.entity.User;
import com.onlinevideo.service.RoleAuthorityService;
import com.onlinevideo.service.impl.RoleAuthorityServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UrlFilter implements Filter {

    private RoleAuthorityService roleAuthorityService = new RoleAuthorityServiceImpl();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("url过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String requestURI = req.getRequestURI();
        //是否是通过jsp访问
        if(requestURI.endsWith(".jsp")&&!("/index_bf.jsp".equals(requestURI))){
            req.setAttribute("msg","链接请求错误，请重新检查");
            req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req,resp);
            return;
        }
        //是否是首页
        if("/".equals(requestURI)||"/index".equals(requestURI)||"/index.html".equals(requestURI)||"/index_bf.jsp".equals(requestURI)) {
            req.getRequestDispatcher("index_bf.jsp").forward(req, resp);
            return;
        }
        if(requestURI.startsWith("/static/")||requestURI.startsWith("/uploadFile/")||requestURI.startsWith("/favicon.ico")) {
            chain.doFilter(request,response);
            return;
        }
        //判断是否是默认的请求
        String action = "";
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类 ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据 得到每个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                req.setAttribute("fileList", list);
                //文件域
                List<FileItem> fileDomain = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    FileItem fileItem = list.get(i);
                    if (fileItem.isFormField()) {
                        req.setAttribute(fileItem.getFieldName(), fileItem.getString("UTF-8"));
                    } else {
                        fileDomain.add(fileItem);
                    }
                }
                action = req.getAttribute("action") != null ? String.valueOf(req.getAttribute("action")) : "";
                if (action.length() > 0) {
                    req.setAttribute("fileDomain", fileDomain);
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }else {
            action = req.getParameter("action");
        }
        if(action==null||action.length()<=0){
            req.setAttribute("msg","链接请求错误，请重新检查");
            req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req,resp);
            return;
        }
        if("/gateway".startsWith(requestURI)){
            for (String gatewayReleaseAction : MyConst.GATEWAY_RELEASE_ACTION) {
                if(gatewayReleaseAction.equals(action)){
                    chain.doFilter(request,response);
                    return;
                }
            }
            HttpSession session = req.getSession();
            User user = (User)session.getAttribute("user");
            User bguser = (User)session.getAttribute("bguser");

            if(user != null) {
                //前台登录用户
                //查找这个用户能够操作的权限
                List<RoleAuthorityDTO> roleAuthorityDTOS = queryUserAuthority(user.getRoleId());
                if (roleAuthorityDTOS.size() <= 0) {
                    //用户角色无访问权限
                    String msg = "<script src='../static/js/jquery-1.11.3.min.js' type='text/javascript'></script><script src='../static/js/sweetalert.min-2.1.2.js' type='text/javascript'></script><script type='text/javascript'>$(function(){swal('警告','该链接不存在', 'error').then(function (isOk){location.href='/';});});</script>";
                    req.setAttribute("msg", msg);
                    req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req, resp);
                    return;
                }
                for (RoleAuthorityDTO roleAuthorityDTO : roleAuthorityDTOS) {
                    String url = requestURI + "?action=" + action;
                    Authority authority = roleAuthorityDTO.getAuthority();
                    if (authority != null) {
                        if (url.equals(authority.getUrl())) {
                            chain.doFilter(request, response);
                            return;
                        }
                    }

                }
                String msg = "<script src='../static/js/jquery-1.11.3.min.js' type='text/javascript'></script><script src='../static/js/sweetalert.min-2.1.2.js' type='text/javascript'></script><script type='text/javascript'>$(function(){swal('警告','该链接不存在', 'error').then(function (isOk){location.href='/';});});</script>";
                req.setAttribute("msg", msg);
                req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req, resp);
                return;
            }else if(bguser !=null){
                //前台登录用户
                //查找这个用户能够操作的权限
                List<RoleAuthorityDTO> roleAuthorityDTOS = queryUserAuthority(bguser.getRoleId());
                if (roleAuthorityDTOS.size() <= 0) {
                    //用户角色无访问权限
                    String msg = "<script src='../static/js/jquery-1.11.3.min.js' type='text/javascript'></script><script src='../static/js/sweetalert.min-2.1.2.js' type='text/javascript'></script><script type='text/javascript'>$(function(){swal('警告','该链接不存在', 'error').then(function (isOk){location.href='/';});});</script>";
                    req.setAttribute("msg", msg);
                    req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req, resp);
                    return;
                }
                for (RoleAuthorityDTO roleAuthorityDTO : roleAuthorityDTOS) {
                    String url = requestURI + "?action=" + action;
                    Authority authority = roleAuthorityDTO.getAuthority();
                    if (authority != null) {
                        if (url.equals(authority.getUrl())) {
                            chain.doFilter(request, response);
                            return;
                        }
                    }
                }
                String msg = "<script src='../static/js/jquery-1.11.3.min.js' type='text/javascript'></script><script src='../static/js/sweetalert.min-2.1.2.js' type='text/javascript'></script><script type='text/javascript'>$(function(){swal('警告','该链接不存在', 'error').then(function (isOk){location.href='/';});});</script>";
                req.setAttribute("msg", msg);
                req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req, resp);
                return;
            }else {
                String msg = "<script src='../static/js/jquery-1.11.3.min.js' type='text/javascript'></script><script src='../static/js/sweetalert.min-2.1.2.js' type='text/javascript'></script><script type='text/javascript'>$(function(){swal('警告','请登录系统访问发送该请求', 'error').then(function (isOk){location.href='../gateway?action=login';});});</script>";
                req.setAttribute("msg", msg);
                req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req, resp);
                return;
            }
        }
        chain.doFilter(request,response);
    }


    private List<RoleAuthorityDTO> queryUserAuthority(Long userId){
        if(userId==null){
           return new ArrayList<>();
        }
        return roleAuthorityService.queryByRoleId(userId);
    }
    @Override
    public void destroy() {
        System.out.println("url过滤器销毁");
    }
}
